package com.ants.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.ants.common.order.Orders;
import com.ants.common.product.Product;
import com.ants.order.feign.FeignProductService;
import com.ants.order.service.OrderService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 蚂蚁会花呗
 * @create 2025/5/22 11:24
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private FeignProductService feignProductService;

    /**
     * 用户下单，买两件商品
     * @param pid
     * @return
     */
    @GetMapping("/buy/{pid}")
    public Orders order(@PathVariable("pid") Integer pid){
        System.out.println("客户下单，调用商品微服务信息");
        Product product = feignProductService.getEntity(pid);
        System.out.println("查询商品信息：" + JSON.toJSONString(product));
        Orders order = new Orders();
        order.setUid(1);//假设是用户id等于1的用户买
        order.setUsername("测试用户2"); //用户的名称是
        order.setPid(pid);//商品的id
        order.setPname(product.getPname()); //商品的名称
        order.setNumber(2); //买两件商品
        order.setPrice(product.getPrice()); //商品的价格
        orderService.save(order);
        return order;
    }


    @RequestMapping("/message1")
    public String message1() {
        return "message1";
    }
    @RequestMapping("/message2")
    public String message2() {
        return "message2";
    }


    @GetMapping("get")
    public IPage<Orders> get(){
        Page<Orders> iPage = new Page<>(1,10);
        return this.orderService.page(iPage);
    }

    @GetMapping("/hello")
    @SentinelResource(value = "helloValue", blockHandler = "handleException")
    public String helloWang() {
        // 模拟业务逻辑，此处仅为示例，实际业务逻辑应放在这里。
        return "Hello, Sentinel!这是正常访问";
    }
    // 定义一个异常处理方法，当流量被拦截时会调用此方法。
    public String handleException(BlockException ex) {
        return "哈哈哈";
    }

}
